import cloud from '@lafjs/cloud'
const WXAPP_OPEN_API_URL = "https://api.weixin.qq.com"

let dbName = "web-users"

export default async function (ctx: FunctionContext) {
  // 获取
  const res = await cloud.fetch.get(`${WXAPP_OPEN_API_URL}/sns/jscode2session `, {
    params: {
      grant_type: "authorization_code",
      appid: "wx9c3827b9e4e2ea96",
      secret: "122cfacb5c3fdab083f0e354b13f8365",
      js_code: ctx.body.jscode
    }
  });

  const res_data = res.data

  // 获取失败
  if (res_data.errcode) {
    return cloud.utils.requestReturn({ msg: res_data.errmsg, code: 500 })
  } else {
    //拿到token
    let token = await searchUser(res_data.openid)
    return cloud.utils.requestReturn({ data: token })
  }
}

let searchUser = async (openid) => {
  let resp = await cloud.nw.db.findByWhereJson({
    dbName,
    whereJson: { wx: { openid } }
  });
  let user_id = null  //用户id
  //如果有这个用户,就直接获取，没有就去新增
  if (resp && resp._id) {
    user_id = resp._id
  } else {
    await cloud.nw.db.add({
      dbName,
      dataJson: { wx: { openid } },
      cancelAddTime: false
    });
    let { _id } = await cloud.nw.db.findByWhereJson({
      dbName,
      whereJson: { wx: { openid } }
    });
    user_id = _id
  }
  return cloud.utils.generateToken(user_id)
}